package com.bw.z.mvp.view.user.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.LogUtils;
import com.bw.z.R;
import com.bw.z.db.DBManager;
import com.bw.z.db.UserTable;
import com.bw.z.db.UserTableDao;
import com.bw.z.utils.SpUtils;

public class NicknameActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView nicknameBack;
    private EditText editNickname;
    private Button nicknameSave;
    private DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nickname);
        initView();
    }

    private void initView() {
        nicknameBack = (ImageView) findViewById(R.id.nickname_back);
        editNickname = (EditText) findViewById(R.id.edit_nickname);
        nicknameSave = (Button) findViewById(R.id.nickname_save);
        nicknameBack.setOnClickListener(this::onClick);
        nicknameSave.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.nickname_back) {
            finish();
        } else {
            String name = editNickname.getText().toString().trim();
            if (name.equals("")) {
                Toast.makeText(NicknameActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent();
                intent.setAction("nickname");
                intent.putExtra("name", name);
                sendBroadcast(intent);

                dbManager = new DBManager(v.getContext());
                UserTableDao userTableDao = dbManager.getDaoSession().getUserTableDao();
                //修改数据库
                Long user_id = SpUtils.readDataLong("user_id");
                UserTable load = userTableDao.load(user_id);
                load.setUser_name(name);
                userTableDao.update(load);
                LogUtils.json(userTableDao.load(user_id));
                finish();

            }
        }
    }
}